package com.huaxin.controller;

import com.huaxin.entity.User;
import com.huaxin.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * @Author Corday
 * @Create 2020/5/22 16:21
 * @用户注册，登录，验证
 */
@Controller
public class UserController {
    //    注入一个服务对象
    @Resource
    private UserService userService;
    //    执行注册
    @RequestMapping("/register")
    //HttpServletRequest request
    //直接通过参数获取前端的参数值,model/Map或HttpSession
    public String regsiter(User user, Model model) {
        //执行注册
        String info = userService.addUser(user);
//        切换页面WEB-INF/js/back_register.jsp
//        model.asMap().put("info",info);
        model.addAttribute("info", info);
        return "back_register";
    }

    //    执行登录
    @RequestMapping("/login")
    public String login(String username, String password, HttpSession session) {//HttpServletRequest request
        //        查询是否有此用户
        User user = userService.queryUserByUsernmae(username, password);
        String mv="";
        //ModelAndView mv与Model/ModelMap的作用域相当于request,作用于一个请求
        if (user == null) {
            session.setAttribute("error", "用户名或密码错误!");
            mv="back_login";
        } else {
            session.setAttribute("username",user.getUsername());
            mv="back_index";
        }
//        切换页面
        return mv;
    }
}
